package com.example.demo.controller;

import com.example.demo.entity.OrderBase;
import com.example.demo.service.OrderBaseService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PaySuccessController {
	private OrderBaseService orderBaseService ;

	public PaySuccessController(OrderBaseService orderBaseService) {
		this.orderBaseService = orderBaseService;
	}

	private volatile int flag = 0;
	/**
	 * 支付宝支付
	 * @param request
	 * @param response
	 */
	@RequestMapping("/zfbSuccess")
	public void paySuccess1(HttpServletRequest request,HttpServletResponse response){
		Map<String, String[]> aliParams = request.getParameterMap();
		System.out.println(aliParams);
		String order_id = aliParams.get("out_trade_no")[0];
		System.out.println(order_id);
//		改变订单状态
		OrderBase orderBase = new OrderBase();
		orderBase.setOrderId(order_id);
		orderBase.setStatus("2");
		orderBaseService.update(orderBase);

		System.out.println("支付成功");
		flag =1;
	}
	@RequestMapping("/wxSuccess")
	public void paySuccess2(HttpServletRequest request,HttpServletResponse response) throws Exception {
//		System.out.println(param);
		// 接收请求参数
		InputStream inStream = request.getInputStream();
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		String xml = new String(outSteam.toByteArray(), "utf-8");
		// 转为Map
		Map<String, String> params = WXPayUtil.xmlToMap(xml);
		outSteam.close();
		inStream.close();

		String order_id = params.get("out_trade_no");
		System.out.println(params);
		OrderBase orderBase = new OrderBase();
		orderBase.setOrderId(order_id);
		orderBase.setStatus("2");
		orderBaseService.update(orderBase);
		flag =1;
	}

	@RequestMapping("/isPayed")
	public int isPayed(){
		return flag;
	}

	@RequestMapping("/changePayed")
	public void changePayed(){
		flag = 0;
	}
}
